<?php
declare (strict_types=1);

namespace app\services\wechat;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/12/12
 * Time: 11:32
 */
use app\services\BaseServices;

//NotifyService类
class NotifyService extends BaseServices
{
    protected $apiKey;
    const AUTH_TAG_LENGTH_BYTE = 16;
    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * Decrypt AEAD_AES_256_GCM ciphertext
     *
     * @param string $associatedData     AES GCM additional authentication data
     * @param string $nonceStr           AES GCM nonce
     * @param string $ciphertext         AES GCM cipher text
     *
     * @return string|bool      Decrypted string on success or FALSE on failure
     */
    public function decryptToString(string $associatedData, string $nonceStr, string $ciphertext)
    {

        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }
        $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
        $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
        return \openssl_decrypt($ctext, 'aes-256-gcm', $this->apiKey, \OPENSSL_RAW_DATA, $nonceStr,
            $authTag, $associatedData);
    }
}
